import React, { useRef, useEffect, useState } from 'react';
import * as echarts from 'echarts';
import { useSize } from 'ahooks';
import { xAxis, yAxis, getXData } from '../chartBase';
import styles from './index.less';

/**
 *
 * @param {Object} options 配置项
 * @param {String} xType 时间轴类型 97、96、days、months
 * @returns
 */

const TRChartLegend = ({ options = {}, xType = '' }) => {
  const chartRef = useRef();
  const chartSize = useSize(chartRef);
  let [chartIns, setChartIns] = useState(null);
  let [myLegends, setMyLegends] = useState([]);

  useEffect(() => {
    chartIns = echarts.init(chartRef?.current);
    setChartIns(chartIns);
    return () => {
      chartIns?.dispose();
      chartIns = null;
    };
  }, []);

  useEffect(() => {
    if (!chartIns || !options) return;
    setTimeout(() => {
      updateChart();
    }, 150);
  }, [JSON.stringify(options)]);

  useEffect(() => {
    setTimeout(() => {
      chartIns?.resize();
    }, 150);
  }, [chartSize]);

  function updateChart() {
    if (!chartIns || !options) return;
    const xData = getXData(xType);
    chartIns?.clear();
    chartIns?.setOption({
      xAxis: {
        ...xAxis,
        data: xData,
      },
      yAxis,
      grid: { top: 30, left: 10, right: 10, bottom: 10, containLabel: true },
      legend: { show: false },
      tooltip: {
        trigger: 'axis',
        formatter: tooltipFormatter,
        axisPointer: {
          type: 'cross',
          snap: false,
        },
      },
      ...options,
    });
    myLegends = (options?.series || []).map((item) => ({
      name: item?.name || '',
      value: item?.data?.[0],
      color: item?.itemStyle?.color || '#fff',
      type: item?.type === 'line' ? item?.lineStyle?.type : '',
      unSelect: false,
    }));
    setMyLegends(myLegends);
  }

  const tooltipFormatter = (params) => {
    const i = params?.[0]?.dataIndex;
    (options?.series || []).map((item, idx) => {
      myLegends[idx].value = item.data[i];
    });
    setMyLegends([...myLegends]);
    return null;
  };

  const onClickLegend = (item) => {
    // 图例点击
    item.unSelect = !item.unSelect;
    chartIns.dispatchAction({
      type: 'legendToggleSelect',
      name: item.name,
    });
    setMyLegends([...myLegends]);
  };

  const renderIcon = ({ type, color, unSelect }) => {
    switch (type) {
      case 'solid':
        return (
          <div className={styles.solid}>
            <div className={styles.solidL} style={!unSelect ? { background: color } : {}} />
            <div className={styles.solidM} style={!unSelect ? { borderColor: color } : {}} />
            <div className={styles.solidR} style={!unSelect ? { background: color } : {}} />
          </div>
        );
      case 'dashed':
        return (
          <div className={styles.dashed}>
            <div className={styles.dashedL} style={!unSelect ? { background: color } : {}} />
            <div className={styles.dashedM} style={!unSelect ? { background: color } : {}} />
            <div className={styles.dashedR} style={!unSelect ? { background: color } : {}} />
          </div>
        );
      default:
        return null;
    }
  };

  const renderValue = (v) => {
    let value = !!v && typeof v === 'object' ? v.value : v;
    if (!!value || value === 0) return value;
    return '-';
  };

  return (
    <div className={styles.chartWrap}>
      <div className={styles.chart}>
        <div ref={chartRef} style={{ width: '100%', height: '100%' }} />
      </div>
      <div className={styles.chartLegend}>
        {myLegends.map((item) => (
          <div
            key={item.name}
            className={`${styles.legendItem} ${item.unSelect && styles.unSelect}`}
            onClick={() => onClickLegend(item)}
          >
            {renderIcon(item)}
            <span className={styles.text}>
              {item.name}: {renderValue(item.value)}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
};

export default TRChartLegend;
